<?php

namespace JsonLowCode\Form;

use BadMethodCallException;
use Closure;
use JsonSerializable;
use JsonLowCode\UI\AppForm;
use JsonLowCode\Factory\FormFactory;
use JsonLowCode\Form;;

class Make extends FormFactory implements JsonSerializable
{
    protected AppForm $form;
    protected Form $build;

    public function __construct(Form $form)
    {
        parent::__construct();
        $this->build = $form;
        $this->form = $form->form();
    }

    public function build(): Form
    {
        return $this->build;
    }

    public function form(): AppForm
    {
        return $this->form;
    }

    /**
     *
     */
    public function setData(): static
    {
        $this->build->setData();
        return $this;
    }

    /**
     * @return
     */
    public function getData()
    {
        return $this->build->getData();
    }

    /**
     * Dynamically handle calls to the class.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     * @throws BadMethodCallException
     */
    public function __call($method, $parameters)
    {
        if (!static::hasMacro($method)) {
            throw new BadMethodCallException(sprintf(
                'Method %s::%s does not exist.', static::class, $method
            ));
        }
        $macro = static::$macros[$method];
        array_unshift($parameters,$this->build);
        $object = new $macro(...$parameters);
        $this->elements[] = $object;
        if ($object instanceof Closure) {
            return call_user_func_array($object->bindTo($this, static::class),$parameters);
        }
        return $object;
    }

    public function jsonSerialize()
    {
        return $this->elements;
    }

}
